package com.zygh.coordinatestore.util;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @author lee
 */
@Component
public class NettyBeanConfig {

    private NettyConfig nettyConfig;


    private NormalUdpServerHandler normalUdpServerHandler;
    @Autowired
    private void setNormalUdpServerHandler(NormalUdpServerHandler normalUdpServerHandler){
        this.normalUdpServerHandler = normalUdpServerHandler;
    }

    @Autowired
    public void setApplicationConfig(NettyConfig nettyConfig) {
        this.nettyConfig = nettyConfig;
    }

    @Bean("bootstrap")
    public Bootstrap bootstrap() {
        EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
        return new Bootstrap()
                .group(eventLoopGroup)
                .channel(NioDatagramChannel.class)
                .option(ChannelOption.WRITE_BUFFER_WATER_MARK,new WriteBufferWaterMark(1,1024*1024*8))
                .handler(normalUdpServerHandler);

    }


    @Bean(name = "udpSocketAddress")
    public InetSocketAddress tcpPort() {
        return new InetSocketAddress(nettyConfig.getPort());
    }
}